﻿using MvcArchStarter.Core.Persistence;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace MvcArchStarter.Infrastructure.Persistence
{
    class DbSetRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private readonly IDbSet<TEntity> dbSet;
        private readonly List<string> includePaths;

        public DbSetRepository(IDbSet<TEntity> dbSet)
        {
            this.dbSet = dbSet;
            includePaths = new List<string>();
        }

        public IQueryable<TEntity> FindAll()
        {
            return this.dbSet;
        }
        public IQueryable<TEntity> FindWhere(Expression<Func<TEntity, bool>> predicate)
        {
            if (includePaths != null && includePaths.Count > 0)
            {
                //IQueryable<TEntity> include = dbSet.Include(includePaths[0]);
                //for (int i = 1; i < includePaths.Count; i++)
                //{
                //    include = include.Include(includePaths[i]);
                //}

                IQueryable<TEntity> include = dbSet;

                includePaths.ForEach(i => include = include.Include(i));

                includePaths.Clear();

                return include.Where(predicate);
            }
            else
            {
                return this.dbSet.Where(predicate);
            }
        }

        public IRepository<TEntity> Include(Expression<Func<TEntity, object>> pathExpression)
        {
            string path = pathExpression.GetExpressionPath();
            return Include(path);
        }

        public IRepository<TEntity> Include(string path)
        {
            includePaths.Add(path);
            return this;
        }

        public void Add(TEntity entity)
        {
            this.dbSet.Add(entity);
        }

        public void Remove(TEntity entity)
        {
            this.dbSet.Remove(entity);
        }
    }
}
